﻿using CuoDing.Core.Extensions;
using CuoDing.Core.Model.Enum;
using CuoDing.Core.Model.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CuoDing.Core.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestFreesqlController : ControllerBase
    {
        private readonly IFreeSql _fsql;
        private readonly ILogger<TestFreesqlController> _logger;
        public TestFreesqlController(IFreeSql fsql, ILogger<TestFreesqlController> logger)
        {
            _fsql = fsql;
            _logger = logger;
        }

        [HttpGet]
        public dynamic TestMultiFreesql()
        {
            DXResult dXResult = new DXResult();
            dXResult.code = DXCode.Success;
            try
            {
                /*
                * 特别重要：
                  1、切换数据库后，后续的操作都是针对该数据库
                  2、切换数据库有两种方式
                     (1)先切换，后操作
                     _fsql.Change("xxxx");
                     _fsql.Select("").....
                     (2)切换与操作都写一起
                     _fsql.Change("xxxx").Select("")....
                  3、不支持事务

                */
                Dictionary<string, object> dict = new Dictionary<string, object>();
                var list1 = _fsql.Select<object>().WithSql("select * from test_user ").ToList<object>("*");//默认数据库为配置项的第一个，MSSQL数据库
                dict.Add("list1", list1);
                var list2 = _fsql.Change("DB2").Select<object>().WithSql("select * from test_user ").ToList<object>("*");//切换到Mysql数据库
                dict.Add("list2", list2);

                dXResult.data = dict;

            }
            catch (Exception ex)
            {
                dXResult.code = DXCode.Failure;
                dXResult.msg = "操作异常";
                _logger.LogError(ex.Message);
            }
            return dXResult;
        }
    }
}
